package com.gymmsystem.GYMMSystem.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gymmsystem.GYMMSystem.entity.MemberCardRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface MemberCardRecordMapper extends BaseMapper<MemberCardRecord> {

    /**
     * 查询会员卡购买记录（包含关联信息）
     */
    @Select("SELECT r.*, u.u_nickname as user_nickname, c.card_name, c.price as card_price " +
            "FROM member_card_records r " +
            "LEFT JOIN users u ON r.user_id = u.user_id " +
            "LEFT JOIN member_card_types c ON r.card_type_id = c.card_type_id " +
            "WHERE r.user_id = #{userId} " +
            "ORDER BY r.created_at DESC")
    List<MemberCardRecord> selectRecordsWithInfo(@Param("userId") Long userId);

    /**
     * 分页查询会员卡购买记录（包含关联信息）
     */
    @Select("SELECT r.*, u.u_nickname as user_nickname, c.card_name, c.price as card_price " +
            "FROM member_card_records r " +
            "LEFT JOIN users u ON r.user_id = u.user_id " +
            "LEFT JOIN member_card_types c ON r.card_type_id = c.card_type_id " +
            "ORDER BY r.created_at DESC")
    IPage<MemberCardRecord> selectRecordsWithInfoPage(Page<MemberCardRecord> page);

    /**
     * 根据用户ID查询购买记录
     */
    @Select("SELECT * FROM member_card_records WHERE user_id = #{userId} ORDER BY created_at DESC")
    List<MemberCardRecord> selectByUserId(@Param("userId") Long userId);

    /**
     * 检查用户是否有有效的会员卡
     */
    @Select("SELECT COUNT(*) FROM member_card_records WHERE user_id = #{userId} AND end_date >= CURDATE()")
    Integer countValidCardsByUserId(@Param("userId") Long userId);
}